package nix.jdbc;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JdbcUtils {

	// 必须配置c3p0-config.xml
	private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
	
	// 事务专用Connection，使用ThreadLocal线程隔离
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

	public static Connection getConnection() throws SQLException {
		Connection con = tl.get();
		// con != null 表示在使用事务，返回事务专用con
		if (con != null) return con;
		// con == null 表示未使用事务，从连接池返回新的con
		return dataSource.getConnection();
	}

	public static DataSource getDataSource() {
		return dataSource;
	}
	
	public static void beginTranscation() throws SQLException {
		Connection con = tl.get();
		if (con != null) throw new SQLException("事务已开启，请勿重复开启！");
		con = getConnection();
		tl.set(con);
		con.setAutoCommit(false);
	}
	
	public static void commitTranscation() throws SQLException {
		Connection con = tl.get();
		if (con == null) throw new SQLException("事务未开启，不能提交！");
		con.commit();
		con.close();
		tl.remove();
		con = null;
	}
	
	public static void rollbackTranscation() throws SQLException {
		Connection con = tl.get();
		if (con == null) throw new SQLException("事务未开启，不能回滚！");
		con.rollback();
		con.close();
		tl.remove();
		con = null;
	}	
	
	public static void releaseConnection(Connection connection) throws SQLException {
		Connection txCon = tl.get();
		// 未使用事务，关闭非事务专用connection
		if (connection != null && txCon != connection) connection.close();
	}
}
